package com.twu.biblioteca.controller;

import com.twu.biblioteca.BibliotecaApp;
import com.twu.biblioteca.DAO.BookDAO;
import com.twu.biblioteca.model.Book;
import com.twu.biblioteca.view.BookListView;

import java.util.Scanner;

/**
 * Created by andreas on 24.04.14.
 */
public class MyBookListController extends AbstractController implements Controller {

    private final BookDAO bookDAO;
    private final BookListView bookListView;

    public MyBookListController(Scanner reader, BibliotecaApp app) {
        super(reader, app);

        bookListView = new BookListView();
        bookDAO = app.getBookDAO();

        println("Please find a list with your currently borrowed books below.\n");
        println(bookListView.render(bookDAO.findMyBooks()));
        printReturnInstructions();

        handleUserInput();
    }

    private void printReturnInstructions() {
        println("");
        println("Choose one of the following options:\n[ID] Enter the ID of the book you want to return\n[Back] Go back to the main menu\n[Quit] quit.");
        println("");
    }

    private void printConfirmationMessage() {
        println("");
        println("Thank you for returning the book.");
        println("");
    }

    private void printCantReturnMessage() {
        println("");
        println("That is not a valid book to return.");
        println("");
    }

    @Override
    public void doHandleUserInput(String input) {
        switch (input) {
            case "Back":
                goTo(Place.MAIN_MENU);
                break;
            case "Quit":
                handleUserInput = false;
                println("Have a nice day!");
                break;
            default:
                if (input.matches("[0-9]+")) {
                    Book book = bookDAO.find(new Integer(input));
                    if (book != null) {
                        if (book.isReserved()) {
                            returnBook(book);
                            printConfirmationMessage();
                            goTo(Place.MY_BOOKS);
                        } else {
                            printCantReturnMessage();
                            goTo(Place.MY_BOOKS);
                        }

                        return;
                    }
                }
                println("Select a valid option!\n");
        }
    }

    private void returnBook(Book book) {
        book.setReserved(false);
    }
}
